package Controller.StudentServlet;

import Dao.SCDao;
import Dao.StudentDao;
import bean.SC;
import bean.Student;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/delete_student")
public class student_delete extends HttpServlet {
    StudentDao studentDao = new StudentDao();
    SCDao scDao = new SCDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String sno = req.getParameter("sno");
        ArrayList<Student> list = null;
        boolean flag = Boolean.parseBoolean(req.getParameter("flag"));
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);

        if (sno != null && sno.length() > 0) {
            if (flag) {
                list = studentDao.delete(sno);
                map.put("msg", "删除成功");
            } else {
                ArrayList<SC> scList = scDao.selectBySno(sno);
                if (scList != null && scList.size() > 0) {
                    map.put("code", 400);
                    map.put("msg", "该学生已经选择课程，是否删除？");
                } else {
                    list = studentDao.delete(sno);
                    map.put("msg", "删除成功");
                }
            }
        } else {
            map.put("code", 401);
            map.put("msg", "请输入学号");
        }
        resp.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
